/* 
 *	Copyright (C) 2007 cooleyes
 *	eyes.cooleyes@gmail.com 
 *
 *  This Program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *   
 *  This Program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *   
 *  You should have received a copy of the GNU General Public License
 *  along with GNU Make; see the file COPYING.  If not, write to
 *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 
 *  http://www.gnu.org/copyleft/gpl.html
 *
 */
 
#include "aac_parser.h"
#include "common/mem64.h"
#include <string.h>

static uint32_t aac_samplerates[] = {96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000};

AacParser::AacParser() {
	initialize();
};

AacParser::~AacParser() {
	close();
};


void AacParser::initialize() {
	is_open = false;
	
	total_samples = 0;
	total_frames = 0;
	current_frame = 0;
	
	frame_index = 0;
	reader = 0;
	output_buffer = 0;
	read_buffer = 0;
	
	codec = 0;
	codec_initialize = false;
	
	memset(&init_data, 0, sizeof(AudioCodecInitData));
}

void AacParser::finalize() {
	if ( reader ) {
		buffered_reader_close(reader);
	}
	if ( frame_index ) {
		free(frame_index);
	}
	if ( output_buffer ) {
		free(output_buffer);
	}
	if ( read_buffer ) {
		free(read_buffer);
	}
	if ( codec ) {
		if ( codec_initialize )
			codec->finalize();
		delete codec;
	}
	initialize();
};


char* AacParser::get_header_info() {
	uint8_t aac_header_buffer[7];
	if ( buffered_reader_read(reader, aac_header_buffer, 7) != 7 ) {
		finalize();
		return "AacParser : read AAC header fail";
	}
	
	if (!((aac_header_buffer[0] == 0xFF)&&((aac_header_buffer[1] & 0xF6) == 0xF0))) {
		finalize();
		return "AacParser : AAC header error";
	}
	init_data.samplerate = (aac_header_buffer[2]&0x3C)>>2;
	init_data.samplerate = aac_samplerates[init_data.samplerate];
	
	init_data.channels = 2;
		
	init_data.sample_bits = 0x10;
	init_data.samples_per_frame = 1024;
	init_data.samples_per_decoded = init_data.samples_per_frame;
	
	aac_data_start = buffered_reader_seek(reader, 0);
	return 0;	
};

char* AacParser::open(const char* filename) {
	
	close();
	
	reader = buffered_reader_open(filename, 65536, 1);
	if ( !reader ) {
		finalize();
		return "AacParser : open buffered_reader fail";
	}
	buffered_reader_seek(reader, 0);
	
	char* result;
	result = get_header_info();
	if ( result != 0 )
		return result;
		
	uint32_t file_size = buffered_reader_length(reader);
	buffered_reader_seek(reader, aac_data_start);
	uint32_t max_frames = (file_size / 0x1000 + 1) * (init_data.samplerate / init_data.samples_per_frame + 1);
	
	frame_index = (AudioFrameIndex*)malloc_64(max_frames * sizeof(AudioFrameIndex));
	if ( frame_index == 0 ) {
		finalize();
		return "AacParser : malloc seek_table fail";
	}   
	
	uint8_t aac_header_buffer[7];
	total_frames = 0;
	init_data.frame_align = 0;
	while(1) {
		if ( buffered_reader_read(reader, aac_header_buffer, 7) != 7 ) {
			break;
		}
		if (!((aac_header_buffer[0] == 0xFF)&&((aac_header_buffer[1] & 0xF6) == 0xF0))) {
			break;
		}
		
		uint32_t frame_size, temp_value;
		temp_value = aac_header_buffer[3];
		temp_value = (temp_value & 0x3) << 11;
		frame_size = temp_value;
		temp_value = aac_header_buffer[4];
		temp_value = temp_value << 3;
		frame_size = frame_size | temp_value;
		temp_value = aac_header_buffer[5];
		temp_value = temp_value >> 5;
		frame_size = frame_size | temp_value;
		            
		if ( total_frames == 0 ) {
			frame_index[total_frames].frame_position = aac_data_start;
			frame_index[total_frames].frame_size = frame_size;
		}
		else {
			frame_index[total_frames].frame_position = frame_index[total_frames-1].frame_position + frame_index[total_frames-1].frame_size;
			frame_index[total_frames].frame_size = frame_size;
		}		
		total_frames++;
		if ( frame_size > init_data.frame_align )
			init_data.frame_align = frame_size;
		buffered_reader_seek(reader, buffered_reader_position(reader)+frame_size-7);
	}
	if ( total_frames == 0 ) {
		finalize();
		return "AacParser : total_frames = 0";
	}
	buffered_reader_seek(reader, aac_data_start);
	total_samples = total_frames * init_data.samples_per_frame;
	
	output_buffer = malloc_64(init_data.samples_per_frame<<2);
	if ( output_buffer == 0 ) {
		finalize();
		return "AacParser : malloc read_buffer fail";
	}
	
	read_buffer = malloc_64(init_data.frame_align);
	if ( read_buffer == 0 ) {
		finalize();
		return "AacParser : malloc output_buffer fail";
	}
	
	codec = AudioCodec::create_audio_codec(AudioCodec::AAC);
	if ( !codec ) {
		finalize();
		return "AacParser : create audio codec fail";
	}
	result = codec->initialize(&init_data);
	if ( result ) {
		finalize();
		return result;
	}
	codec_initialize = true;
	
	is_open = true;
	return 0;
};

void AacParser::close() {
	if ( is_open ) {
		finalize();
	}
};
	
uint32_t AacParser::get_samplerate() {
	return init_data.samplerate;
};

uint32_t AacParser::get_channels() {
	return init_data.channels;
};

uint64_t AacParser::get_duration() {
	uint64_t duration = 1000000LL*total_samples/init_data.samplerate;
	return duration;
};
	
uint32_t AacParser::get_samples_per_frame() {
	return init_data.samples_per_frame;
};

uint32_t AacParser::get_max_samples_per_frame() {
	return init_data.samples_per_frame;
};

uint64_t AacParser::seek_time(uint64_t time) {
	uint32_t samples = (uint32_t)(time*init_data.samplerate/1000000LL);
	if ( samples > total_samples )
		samples = total_samples;
	
	current_frame = samples/init_data.samples_per_frame;
	
	if (current_frame >= total_frames)
		current_frame = total_frames - 1;
	
	buffered_reader_seek(reader, frame_index[current_frame].frame_position);
	
	uint64_t current = 1000000LL*current_frame*init_data.samples_per_frame/init_data.samplerate;
	return current;
};

char* AacParser::get_frame(void** pcm, uint32_t* samples) {
	
	if ( !is_open )
		return "AacParser : parser is not open";
	
	if ( current_frame >= total_frames ) {
		*pcm = output_buffer;
		*samples = 0;
	}
	else {
		memset(read_buffer, 0, init_data.frame_align);
		uint32_t read_size;
		read_size = buffered_reader_read(reader, read_buffer, frame_index[current_frame].frame_size);
		if ( read_size != (frame_index[current_frame].frame_size) ) {
			*pcm = output_buffer;
			*samples = 0;
		}
		else {
			current_frame++;
			memmove(read_buffer, (uint8_t*)read_buffer+7, read_size-7);
			memset(output_buffer, 0, init_data.samples_per_frame << 2);
			int32_t get_samples = codec->decode(read_buffer, read_size-7, output_buffer);
			*samples = (get_samples<0) ? 0 : get_samples;
			*pcm = output_buffer;
		}
	}
	return 0;
};


